

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.xml.transform.TransformerException;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import com.herohead.*;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;

public class checkUV {

	
	private static org.apache.log4j.Logger log= Logger.getLogger(checkUV.class);
	static PropertiesConfiguration config;
	static Boolean sendEmail = false;

	private static String getDate(String[] s){
		String s1 = s[4];
		String d = (s1.split("AS-IS\""))[1].trim();
		return d;
	}

	public static void main(String[] args) throws IOException, ConfigurationException, NoSuchAlgorithmException, TransformerException {

		config = new PropertiesConfiguration("checkUV.config");
		config.setAutoSave(true);

		Misc m = new Misc();
		CDLogger l = new CDLogger();
		l.programStart(log);
		
		String hashString = null;
		String hashEmail = null;
		String emailBody = "";

		String sURL = config.getString("URL");
		String sSearchFor = config.getString("SearchFor");

		// TODO Auto-generated method stub
		URL url = new URL(sURL);
		log.debug("Looking up " + url);
		URLConnection con = url.openConnection();
		log.debug("Connected to " + url);
		InputStream in = con.getInputStream();
		String encoding = con.getContentEncoding();
		encoding = encoding == null ? "UTF-8" : encoding;
		String body = IOUtils.toString(in, encoding);
		log.debug("Got file data");
		String[] lines = body.split("\n");
		String onLineDateUpdate = getDate(lines);
		config.setProperty("onLineDate", onLineDateUpdate);
		log.debug("Got file date " + onLineDateUpdate);
		//System.out.println(body);


		//System.out.println(onLineDateUpdate);
		// quit if no change.

		//hashString = m.hashmd5(body);

		String ss = sSearchFor;
		String[] sss = ss.toLowerCase().split(",");

		for (String line : lines) {
			String lc = line.toLowerCase();
			for (String ssss : sss) {
				if (lc.contains(ssss))  {
					emailBody += line;
				}
			}
		}


		hashEmail = m.hashmd5(emailBody);
		log.debug("Comparing hashes to determine if different");
		if (!config.containsKey("EmailHash")) {
			log.debug("No parameter EmailHash in the config file - adding");
			config.setProperty("EmailHash", hashEmail);
			config.save();
			config.reload();
			sendEmail = true;
		} 
		log.debug("Comparing new hash to stored hash");
		if (!config.getString("EmailHash").equalsIgnoreCase(hashEmail))  {
			sendEmail = true;
			log.debug("Hash different setting for email");
			config.setProperty("EmailHash", hashEmail);
			log.debug("Storing new hash");
			config.save();
		}

		//System.out.println(m.hashmd5(emailBody));
		//System.out.println(emailBody);
		//System.out.println(sendEmail);
		log.debug("Updating last run in config file");
		config.setProperty("LastRan", m.getTimestamp());
		if (!sendEmail)  {
			log.info("No new data -  no email to send - quiting program");
			l.programStop(log);
			System.exit(0);
		}
		log.debug("Updating LastEmailSent in config file");
		config.setProperty("LastEmailSent", m.getTimestamp());

		Xml xm = new Xml();
		log.debug("Creating XML file for email");
		String xmlemail = xm.sendEmail("herohead@gmail.com", "kd8phi@gmail.com", "Universal Radio Used Ham Radio", emailBody, "smtp");

		//System.out.println(xmlemail);
		log.debug("Setting up for publishing email");
		Rabbit_publish rmq = new Rabbit_publish();

		rmq.setHostname("rabbitmq.hh.cd");

		rmq.setLogin("backup", "networker","backup");
		Channel ch = rmq.setupChannel();

		AMQP.BasicProperties properties = new AMQP.BasicProperties();
		properties.setDeliveryMode(2);

		boolean durable = true;
		String queue = "email";
		ch.queueDeclare(queue, durable, false, false, null);
		ch.basicPublish("", queue, properties, xmlemail.getBytes());
		log.debug("Publishing email");
		rmq.closeChannel();
		l.programStop(log);
		log.info("Program closing - after publishing email");
		System.exit(0);

	}


}
